import com.zgg.core.config.MongoClient
import com.zgg.core.utils.awaitResult
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 * @author zhouganggui
 * @email 1641583112@qq.com
 * @date 2021/6/30 13:32
 * @Descript:
 */
class ExcelMessageDao {
    //原生利用携程的方法使回调方法具有放回值
    suspend fun saveJsonObjectExec(tableName: String, jsonArray: JsonObject): String {
        val ret: AsyncResult<String> = suspendCoroutine { c ->
            saveJsonObject(tableName, jsonArray) {
                c.resume(it)
            }
        }
        return ret.result()
    }

    fun saveJsonObject(tableName: String, jsonObject: JsonObject, collback: (AsyncResult<String>) -> Unit) {
        MongoClient.defMongoClient?.save(tableName, jsonObject, collback)
    }

    //等待并获取结果 封装后的方法
    suspend fun saveJsonArrayExec(tableName: String, jsonArray: JsonArray): Int {
        return awaitResult { saveJsonArray(tableName, jsonArray, it) }
    }

    private fun saveJsonArray(tableName: String, jsonArray: JsonArray, collback: (AsyncResult<Int>) -> Unit) {
        val command = JsonObject()
                .put("insert", tableName)
                .put("documents", jsonArray)
                .put("ordered", false)
        MongoClient.defMongoClient?.runCommand("insert", command) {
            if (it.succeeded()) {
                collback(Future.succeededFuture(it.result().getInteger("n", 0)))
            } else {
                collback(Future.failedFuture(it.cause()))
            }
        }
    }

}